<?php


namespace apps\marriage\core\service;


use apps\marriage\core\logic\FileLogic;
use apps\marriage\core\logic\RegionLogic;
use apps\marriage\core\model\Course;
use think\Exception;
use vm\com\BaseService;

class CourseService extends BaseService
{
    /**
     * @var RegionLogic
     */
    private $regionLogic;

    protected function init()
    {
        parent::init();
        $this->regionLogic = logic('Region', LOGIC_NAMESPACE);
    }

    /**
     * @return Course
     */
    protected function getModel()
    {
        return new Course();
    }

    /**
     * @return BaseService|SiteConfigService
     */
    private function getSiteConfigService()
    {
        return service('SiteConfig', SERVICE_NAMESPACE);
    }

    /**
     * @return FileLogic
     */
    private function getFileLogic()
    {
        return logic('File', LOGIC_NAMESPACE);
    }

    public function format($data)
    {
        $data['region'] = '';
        $regions = $this->regionLogic->parents($data['region_id']);
        foreach ($regions as $region) {
            $data['region'] .= $region['region_name'];
        }
        $file = $this->getFileLogic()->file($data['img_id']);
        $data['img_url'] = $file['url'];

        return $data;
    }

    public function getSharePoster($courseId, $fromuid)
    {
        $hash = md5($courseId . $fromuid);
        $path = 'uploads/share_poster/course/' . $hash{0} . '/' . $hash{1} . '/' . $courseId . '/' . $fromuid . '.jpg';
        $url = request()->scheme() . '://' . request()->host() . '/' . getContextPath() . $path;
        if (is_file(WWW_PATH . $path)) {
            return $url;
        }
        if (!is_dir(dirname(WWW_PATH . $path))) {
            makeDir(dirname(WWW_PATH . $path));
        }
        $tempDir = WWW_PATH . 'uploads/temp/' . date('Ymd') . '/';
        if (!is_dir($tempDir)) {
            makeDir($tempDir);
        }
        $course = $this->getByPk($courseId);
        if(empty($course)) {
            throw new Exception('课程不存在');
        }
        $course = $this->format($course);

        $fontfile = DOC_PATH . 'data/font/Alibaba-PuHuiTi-Regular.otf';
        $textColor = '123,104,238';

        $texts = [];
        $images = [];

        $fname = grabRemoteFile($course['img_url'], $tempDir);
        $img = $tempDir . $fname;
        $images[] = [
            'url' => $img,       //图片资源路径
            'left' => 60,
            'top' => 180,
            'stream' => 0,             //图片资源是否是字符串图像流
            'right' => 0,
            'bottom' => 0,
            'width' => 630,
            'height' => 360,
            'opacity' => 100
        ];

        $str = $course['name'];
        $strRows = rowSubstr($str, 2, 23, false);
        $fontSize = 20;
//        $strPos = imagettfbbox($fontSize, 0, $fontfile, $str);
//        $strLineHeight = $strPos[1] - $strPos[7];
        $texts[] = [
            'text' => implode("\n", $strRows),
            'left' => 70,
            'top' => 580,
            'fontPath' => $fontfile,     //字体文件
            'fontSize' => $fontSize,   //字号
            'fontColor' => '0,0,0',       //字体颜色
            'angle' => 0
        ];

        // 生成二维码
        $mpSite = $this->getSiteConfigService()->getValueByCode('mp_site');
        require_once EXTEND_PATH . 'vm/org/phpqrcode.php';
        $qrUrl = $mpSite . '/college_course?id='.$courseId.'&replace=1&fromuid=' . $fromuid;
        $qrFile = $tempDir . 'qrcode/' . time() . '_' . rand_string(6) . '.png';
        if(!is_dir(dirname($qrFile))) {
            makeDir(dirname($qrFile));
        }
        \QRcode::png($qrUrl, $qrFile);
        $images[] = [
            'url' => $qrFile,       //图片资源路径
            'left' => 145,
            'top' => 780,
            'stream' => 0,             //图片资源是否是字符串图像流
            'right' => 0,
            'bottom' => 0,
            'width' => 200,
            'height' => 200,
            'opacity' => 100
        ];

        $config = [
            'image' => $images,
            'text' => $texts,
            'background' => DOC_PATH . 'data/images/share_poster_3.jpg'
        ];
        createPoster($config, WWW_PATH . $path);
        return $url;
    }

    public function getSignInQrCodeImg($courseId)
    {
        // 生成二维码
        $mpSite = $this->getSiteConfigService()->getValueByCode('mp_site');
        require_once EXTEND_PATH . 'vm/org/phpqrcode.php';
        $qrUrl = $mpSite . '/college_course_signin?id='.$courseId;
        ob_start();//开启缓冲区
        \QRcode::png($qrUrl, false, 'L', 10, 1);//生成二维码
        $img = ob_get_contents();//获取缓冲区内容
        ob_end_clean();//清除缓冲区内容
        $imgData = 'data:png;base64,' . chunk_split(base64_encode($img));//转base64
        ob_flush();
        return $imgData;
    }
}